package cn.edu.ldu.communityqa.communityqa.controller;

import cn.edu.ldu.communityqa.communityqa.entity.User;
import cn.edu.ldu.communityqa.communityqa.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @GetMapping
    public Object findAll(HttpServletRequest request) {
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        if (page == null || limit == null) {
            return userService.findAll();
        } else {
            return userService.findAll(Integer.parseInt(page), Integer.parseInt(limit));
        }
    }

    @PostMapping
    public int save(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping
    public int update(@RequestBody User user) {
        return userService.update(user);
    }

    @DeleteMapping("/{id}")
    public int deleteById(@PathVariable Long id) {
        return userService.deleteById(id);
    }
}
